<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>文件上传相关</title>
  </head>
  <body>
    <!--

      1. form表单提交，注意 enctype 需要设置为 multipart/form-data

     -->
    <form action="/xxx" method="post" enctype="multipart/form-data">
      <input type="file" name="avatar" />

      <button>提交</button>
    </form>

    <div>
      <h1>jquery ajax || axios ajax</h1>
      <input type="file" id="file" />
      <button id="btn">点我，发送请求</button>
    </div>

    <!-- https://www.bootcdn.cn/ -->

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
    <script>
      $("#btn").click(() => {
        // // 1. new FormData()
        // const formData = new FormData();
        // formData.append("avatar", $("#file")[0].files[0]);

        // // $ajax.post("http://localhost:3000/xxx", formData, );
        // $.ajax({
        //   url: "http://localhost:3000/xxx",
        //   // method: "POST",
        //   type: "POST",
        //   // 请求体
        //   data: formData,
        //   //...
        //   processData: false, // 注意
        //   contentType: false, // 注意
        //   success: function (response) {
        //     console.log(response);
        //   },
        // });

        const formData = new FormData();
        formData.append("avatar", document.querySelector("#file").files[0]);

        // axios({
        //   url: "http://localhost:3000/xxx",
        //   method: "POST",
        //   // 请求体
        //   data: formData,
        //   // 设置一些请求头
        //   headers: {
        //     "Content-Type": "multipart/form-data",
        //   },
        // }).then((response) => {
        //   console.log(response);
        // });

        axios
          .post("http://localhost:3000/xxx", formData, {
            // 其余配置项
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
          .then((response) => {
            console.log(response);
          });
      });
    </script>
  </body>
</html>
